<template>
  <div class="main_box">

    <el-row class="header-row">
      <el-col v-if="userRole != 3">
        <div class="search_wrap">
          <el-form
            :inline="true"
            :model="filters"
            class="demo-form-inline"
            ref="searchForm"
          >
            <el-form-item>
              <el-select
                v-model="filters.businessId"
                placeholder="请选择商户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in businessList"
                  :value="item.id"
                  :label="item.name"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="content">
              <el-input
                v-model="filters.content"
                placeholder="文件名"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item prop="businessId">
              <el-button icon="el-icon-search" type="primary" @click="onSearch"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-left" @click="resetForm"
                >重置</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-upload"
                type="danger"
                @click="handleShowUpload"
                >上传图片</el-button
              >
            </el-form-item>

            <el-form-item v-if="env=='development'">
              <el-upload style="display: inline-block;" action="#" :auto-upload="false" :show-file-list="false" multiple :on-change="handleUploadWeixin" accept=".png,.jpg,.jpeg,.xlsx">
                <el-button>
                  上传微信小程序图片
                </el-button>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip class="refrush" content="刷新" placement="top">
            <el-button
              circle
              icon="el-icon-refresh-right"
              @click="reload"
              size="mini"
            ></el-button>
          </el-tooltip>
          <div>
            <el-tabs v-model="filters.type" @tab-click="handleTabChange">
              <el-tab-pane label="图片" name="1"> </el-tab-pane>
              <el-tab-pane label="视频" name="2"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <div
        class="table-wrapper"
        element-loading-text="数据加载中，请稍后..."
        v-loading="loading"
        :style="{ height: this.maxHeight }"
      >
        <div v-for="item in dataList">
          <el-image
            title="点击预览"
            class="img-wrapper"
            v-show="item.type == 1"
            fit="cover"
            :src="item.url"
            :preview-src-list="urlList"
          >
          </el-image>
          <video
            :src="item.url"
            controls
            class="video-wrapper"
            v-show="item.type == 2"
          >
            <h2>我们很抱歉，您的浏览器<strong>不支持video标签</strong></h2>
            <a href="https://www.google.cn/chrome/">点击这里下载浏览器</a>
          </video>
          <div class="text">{{ item.content }}</div>
        </div>
        <div class="empty" v-show="dataList.length == 0">
          对不起，没有找到相关数据！
        </div>
      </div>
      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[30, 50, 80]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <el-dialog
      :visible.sync="upload.show"
      title="上传公共图库"
      center
      width="999px"
      :close-on-click-modal="false"
    >
      <div class="upload-filter">
        <el-select
          style="margin-right: 10px;"
          clearable
          filterable
          v-model="upload.businessId"
          placeholder="请选择商户"
          @change="handleBusinessChange"
        >
          <el-option
            v-for="item in businessList"
            :value="item.id"
            :label="item.name"
            :key="item.id"
          ></el-option>
        </el-select>
        <el-cascader
          placeholder="请选择分类"
          filterable
          clearable
          v-model="upload.classifyIds"
          :options="upload.classifyList"
          :props="{ label: 'classifyName', value: 'serverClassifyId' }"
        ></el-cascader>
      </div>
      <div class="upload-wrapper">
        <div class="img-item" v-for="(item, index) in upload.list">
          <el-image
            v-if="item.type == 1"
            :src="item.blobUrl"
            :preview-src-list="[item.blobUrl]"
            fit="cover"
          ></el-image>
          <video :src="item.blobUrl" controls v-else>
            <h2>我们很抱歉，您的浏览器<strong>不支持video标签</strong></h2>
            <a href="https://www.google.cn/chrome/">点击这里下载浏览器</a>
          </video>
          <el-input
            v-model="item.name"
            placeholder="请输入文件名字"
            clearble
          ></el-input>
          <span
            @click="upload.list.splice(index, 1)"
            class="el-icon-circle-close"
          ></span>
        </div>
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :show-file-list="false"
          multiple
          accept=".png,.jpg,.jpeg,.bmp,.mp4,.m2v,.mkv"
          action="#"
          :auto-upload="false"
          :on-change="handleSelectImgs"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div slot="footer">
        <el-button @click="confirmUpload" type="primary">确定</el-button>
        <el-button @click="upload.show = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { throttle } from "lodash-es";
import CommonImageApi from "@/api/goods/commonImage";
import BusinessApi from "@/api/business/business";
import uploadOssFn,{uploadWeixinImg} from "@/utils/uploadOssFn";
import ServerClassifyApi from "@/api/server/serverClassify";
import {containerScrollToTop} from "../../utils";
export default {
  name: "CommonImageManagement",
  inject: ["reload"], //注入局部刷新
  data() {
    return {
      env:"",
      userRole: "",
      page: {
        pageNo: 1,
        pageSize: 30,
        pageTotal: 0,
        totalPage: 0
      },
      filters: {
        businessId: "",
        content: "",
        type: "1"
      },
      upload: {
        show: false,
        list: [],
        businessId: "",
        classifyIds: [],
        classifyList: []
      },
      maxHeight: "",
      loading: false,
      businessList: [],
      dataList: []
    };
  },
  computed: {
    urlList() {
      return this.filters.type == 1 ? this.dataList.map(item => item.url) : [];
    }
  },
  mounted() {
    this.userRole = this.$store.getters.userRole;
    this.getTableHeight();
    this.listData();
    this.getBusinessList();
    this.env=process.env.MODE
  },
  methods: {
    getTableHeight() {
      this.$nextTick(function() {
        this.maxHeight =
          window.innerHeight - this.$refs.tableRow.$el.offsetTop - 76 + "px";
        window.onresize = () => {
          this.maxHeight =
            window.innerHeight - this.$refs.tableRow.$el.offsetTop - 76 + "px";
        };
      });
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data;
      });
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listData();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listData();
    },
    handleTabChange() {
      this.listData();
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch()
    },
    handleShowUpload() {
      this.upload = this.$options.data().upload;
      this.upload.show = true;
    },
    async getClassifyList() {
      let params = {
        level: 2,
        businessId: this.upload.businessId
      };
      const { data } = await ServerClassifyApi.listServerClassify(params);
      this.upload.classifyList = data || [];
    },
    async handleBusinessChange() {
      const { upload } = this;
      upload.classifyIds = [];
      if (upload.businessId) {
        this.getClassifyList();
      } else {
        upload.classifyList = [];
      }
    },
    handleSelectImgs(file, fileList) {
      fileList.forEach(item => {
        this.$set(item, "blobUrl", URL.createObjectURL(item.raw));
        this.$set(item, "type", this.$Utils.getFileType(item.name));
        item.name = item.name.split(".")[0];
      });
      this.upload.list = this.upload.list.concat(fileList);
      this.$refs.uploadRef.clearFiles();
    },
    async confirmUpload() {
      const { list, businessId, classifyIds } = this.upload;
      if (!businessId) return this.$message.error("请选择商户");
      if (!classifyIds.length) return this.$message.error("请选择分类");

      if (list.length === 0) return this.$message.error("请选择图片或者视频");
      for (let item of list) {
        if (!item.name) return this.$message.error("请填写图片或视频名称");
      }
      list.forEach(
        item => (item.type = this.$Utils.getFileType(item.raw.name))
      );
      const loading = this.$loading({
        lock: true,
        text: "上传文件中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        const res = await uploadOssFn(list, "common");
        const params = {
          list: res.map(item => ({
            url: item.url,
            content: item.name,
            type: item.type
          })),
          businessId,
          serverClassifyId: classifyIds[0] || "",
          thirdclassifyId: classifyIds[1] || ""
        };
        await CommonImageApi.batchAddImage(params);
        this.upload.show = false;
        this.listData();
      } finally {
        loading.close();
      }
    },
    listData(isAdd) {
      let params = {
        type: this.filters.type,
        content: this.filters.content,
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      };
      if (this.userRole != 3) {
        params.businessId = this.filters.businessId;
      }
      this.loading = true;
      CommonImageApi.listCommonImage(params)
        .then(res => {
          this.page.pageTotal = res.data.total;
          this.page.totalPage = res.data.totalPage;
          if (isAdd) {
            this.dataList = this.dataList.concat(res.data.list);
          } else {
            this.dataList = res.data.list;
          }
          containerScrollToTop('table-wrapper')
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async handleUploadWeixin(file){
      // const res = await uploadOssFn([file], "common/excel_model");
      const res = await uploadWeixinImg([file], "common");
      console.log(res[0].url)
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/views/content.scss";
</style>
<style lang="scss" scoped>
.upload-filter {
  margin-bottom: 20px;
}
.upload-wrapper {
  padding-top: 5px;
  display: flex;
  flex-wrap: wrap;
  max-height: 600px;
  overflow: auto;
  .img-item {
    width: 178px;
    height: 178px;
    z-index: 9;
    // box-sizing: border-box;
    margin: 0 10px 20px 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    position: relative;
    .el-image,
    video {
      width: 168px;
      height: 120px;
    }
    .el-input {
      width: 100%;
    }
    .el-icon-circle-close {
      position: absolute;
      font-size: 24px;
      top: -4px;
      right: -4px;
      z-index: 10;
    }
  }
  .avatar-uploader::v-deep {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
.opration_wrap {
  align-items: center;

  .el-tabs {
    &::v-deep .el-tabs__header {
      margin-bottom: 5px;

      .el-tabs__nav-wrap {
        &::after {
          display: none;
        }
      }
    }
  }

  .refrush {
    width: 30px;
    height: 30px;
  }
}

.table-wrapper {
  border: 1px solid #e6e6e6;
  display: grid;
  display: -ms-grid;
  justify-content: space-between;
  align-content: start;
  grid-template-columns: repeat(auto-fill, 170px);
  -ms-grid-columns: repeat(auto-fill, 170px);
  grid-gap: 10px;
  padding: 10px 4px;
  overflow: auto;

  .el-image,
  video {
    width: 170px;
    height: 170px;
    vertical-align: bottom;
  }

  .text {
    text-align: center;
    padding-top: 10px;
  }

  .empty {
    text-align: center;
    margin: 40px auto;
    color: #909399;
    font-size: 14px;
    align-self: center;
    grid-column: 1 / -1;
    -ms-grid-column: 1 / -1;
  }
}
</style>
